<!--
    * Time    : 2020-12-22 13:47:54
    * Author  : zhangTj
    * Desc    : 地图页面
-->

<template>
    <div class="w750" :style="{ '--themescolor': themes.color }">
        <div id="container" class="w-100" :style="{ height: '45%' }"></div>
        <van-popup v-model="show" :overlay="false" position="bottom" :style="{ height: '55%' }">
            <div class="d-flex flex-column h-100">
                <div @click="toSearch" class="m-1 p-1 font-14 bg-f8 rounded-10">
                    <span class="iconfont iconsearch mr-1" style="font-size: 14px"></span>
                    <span>搜索地点</span>
                </div>

                <van-list
                    v-if="!partLoading"
                    v-model="loading"
                    :finished="finished"
                    :immediate-check="false"
                    finished-text="没有更多了"
                    @load="loadMore"
					style="padding-bottom: 64px;"
                >
                    <div class="p-1 flex-1" ref="pointList">
                        <div
                            @click="chooseItem(item)"
                            v-for="(item, index) in list"
                            :key="index"
                            class="d-flex font-16 border-bottom mb-1 pb-1 cursor-pointer"
                        >
                            <div class="mr">
                                <span class="iconfont iconlocation"></span>
                            </div>
                            <div class="flex-1" style="width: 200px">
                                <div class="line-clamp1">{{ item.name }}</div>
                                <div class="font-12 text-999 mt line-clamp1">
                                    {{ item.address }}
                                </div>
                            </div>
                            <div v-if="activeItem.id == item.id">
                                <span class="iconfont iconselectItem text-main" style="font-size: 14px"></span>
                            </div>
                        </div>
                    </div>
					<!-- <div v-for="item in 1000">
						{{item}}
					</div> -->
                </van-list>
                <part-loading v-model="partLoading" backgroundColor="#fff" size="24px" :color="themes.color" />

                <div class="w-100 bg-fff border-top position-fixed bottom-0" style="height: 64px">
                    <div class="p-1">
                        <van-button @click="submitItem" class="w-100" round :color="themes.color" type="info">确认地点</van-button>
                    </div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { Toast } from 'vant'
import { geolocationFunc, placeSearchFunc } from '@/utils/mapUtils'
import PartLoading from '@/components/PartLoading/PartLoading'

export default {
    name: '',
    components: { PartLoading },
    data() {
        return {
            lng: '', // 传进来的维度
            lat: '', // 传进来的经度
            source: 'order', // 来源: order => 从订单的自提点选择中进来(selfPoint); point => 从创建自提点页面进来(pointActive)
            map: '', // 地图实例
            show: true, // 弹出层
            loading: false,
            finished: false,
            list: [], // 数据列表
            pageIndex: 1, // 页码
            pageSize: 20, // 页数
            count: 0, // 总数目
            activeItem: '', // 选中的地点
            positionPicker: '',
            centerMarker: null, // 地图中心点marker
            placeSearch: null, // 搜索插件实例
            partLoading: true, // 局部loading
            selectPlace: null, // 搜索的地图点
            firstLoad: true, // 是否第一次加载

            focusOnPoint: true // 是否地图视野在定位之中
        }
    },
    computed: {
        ...mapState(['themes'])
    },
    watch: {},
    created() {},
    destroyed() {},
    mounted() {
        // 是从哪个页面进入的
        // const source =
        if (this.$route.query.source) {
            this.source = this.$route.query.source
        }
        if (this.$route.query.lng) {
            this.lng = this.$route.query.lng
        }
        if (this.$route.query.lat) {
            this.lat = this.$route.query.lat
        }
        this.initMap(this.source)
    },
    methods: {
        initMap() {
            this.map = new AMap.Map('container', {
                zoom: 17,
                resizeEnable: true,
                scrollWheel: true, // 是否支持鼠标滚轮放大缩小
                lang: 'zh_cn', //设置地图语言类型
                viewMode: '2D', //设置地图模式
                jogEnable: false // 是否使用缓动效果
            })
			
            // 添加自动定位插件
            this.map.on('complete', () => {
                // 搜索地图点的点
                if (sessionStorage.getItem('selectPlace')) {
                    this.selectPlace = JSON.parse(sessionStorage.getItem('selectPlace'))
                }

                if (this.selectPlace || (this.lng && this.lng)) {
                    this.focusOnPoint = false
                }

                // 自动定位插件
                let geolocation = geolocationFunc({ zoomToAccuracy: this.focusOnPoint })
                geolocation.getCurrentPosition(this.locationComplete)
                this.map.addControl(geolocation)

                // 手动定位的回调函数
                AMap.event.addListener(geolocation, 'complete', (result) => {
                    if (result.info == 'SUCCESS' && result.type == 'complete') {
						this.$store.commit('setCurLocation', result)
						// this.getPOI(result.position)
                        // 如果存在搜索选择点,则搜索附近的点
                        if (this.firstLoad && this.selectPlace) {
                            this.getPOI(new AMap.LngLat(this.selectPlace.location.lng, this.selectPlace.location.lat))
                        } else if (result.position.lng && result.position.lat) {
                            this.getPOI(new AMap.LngLat(result.position.lng, result.position.lat))
                        }
                        if (!this.firstLoad) {
                            this.getPOI(result.position)
                        }
                    }
                })

                // 搜索插件
                this.placeSearch = placeSearchFunc({ pageSize: this.pageSize, pageIndex: this.pageIndex })
            })

            this.map.on('mapmove', this.mapMove)
            this.map.on('moveend', this.mapMoveEnd)
            this.map.on('dragend', this.drangend) // 拖拽结束时触发
            this.map.on('zoomend', this.drangend) // 缩放地图结束时触发
        },

        // 自动定位回调函数
        locationComplete(status, result) {
            if (status !== 'complete') {
                Toast.fail('定位失败')
                return
            }

            const centerPoint = new AMap.LngLat(result.position.lng, result.position.lat)
            this.addCenterMarker(centerPoint)

            // 设置地图中心点
            if (this.selectPlace) {
                this.map.setCenter(new AMap.LngLat(this.selectPlace.location.lng, this.selectPlace.location.lat))
            } else if (this.lng && this.lat) {
                this.map.setCenter(new AMap.LngLat(this.lng, this.lat))
            } else {
                this.map.setCenter(centerPoint)
            }
        },

        // 添加中心标记点
        addCenterMarker(lngLat) {
            this.centerMarker = new AMap.Marker({
                position: lngLat
            })
            this.centerMarker.setMap(this.map)
        },

        // 选择地点
        chooseItem(item) {
            this.map.setCenter(item.location)
            this.activeItem = item
        },

        // 地图平移时触发
        mapMove() {
            this.centerMarker.setPosition(this.map.getCenter())
        },

        // 地图平移结束
        mapMoveEnd() {
            this.centerMarker.setAnimation('AMAP_ANIMATION_DROP')
        },

        // 拖拽地图结束触发
        drangend() {
            this.partLoading = true
            this.centerMarker.setAnimation('AMAP_ANIMATION_DROP')
            this.list = []
            this.activeItem = ''
            this.getPOI(this.map.getCenter())
        },

        // 搜索指定点附近的POI
        getPOI(point, distance = 2000) {
            this.placeSearch.searchNearBy('', point, distance, (status, result) => {
                if (status == 'complete' && result.info == 'OK') {
                    this.list = result.poiList.pois
                    this.count = result.poiList.count
                    this.partLoading = false

                    // 如果是第一次加载并且存在搜索选择的地点,则将其搜索选择的地点放在第一位, 并勾选, 最后移除缓存
                    if (this.firstLoad && this.selectPlace) {
                        this.list.unshift(this.selectPlace)
                        this.firstLoad = false
                        this.activeItem = this.selectPlace
                    }
                }
            })
        },

        // 加载更多POI
        loadMore() {
			console.log(111)
            if (this.list.length < this.count) {
                this.pageIndex++
                this.placeSearch.setPageIndex(this.pageIndex)
                this.placeSearch.searchNearBy('', this.map.getCenter(), 2000, (status, result) => {
                    if (status == 'complete' && result.info == 'OK') {
                        this.list = this.list.concat(result.poiList.pois)
                        this.count = result.poiList.count
                        this.loading = false
                    }
                })
            } else {
                this.finished = true
            }
        },

        // 确定选择的地点
        submitItem() {
            if (!this.activeItem) return void this.$toast('请选择地点')

            sessionStorage.setItem('location', JSON.stringify(this.activeItem))
            sessionStorage.removeItem('selectPlace')
            this.$router.back() // 返回上一个页面
        },

        // 去搜索
        toSearch() {
            this.$router.push({ name: 'mapSearch' })
        }
    }
}
</script>

<style scoped></style>
